import axios from "axios";
import Qs from "qs";
import $store from "../store";
import toLogin from "@libs/login";
import { VUE_APP_API_URL, storeId } from "@utils/index";

const instance = axios.create({
  transformRequest: [
    function(data) {
      data = Qs.stringify(data);
      return data;
    }
  ],
  baseURL: "http://www.yjlive.cn:8081/",
  timeout: 30000
});
instance.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded";
const defaultOpt = { login: true };
const methodsToken = [
  "user.info",
  "user.editinfo",
  "user.changeavatar",
  "user.logout",
  "user.addgoodsbrowsing",
  "user.delgoodsbrowsing",
  "user.goodsbrowsing",
  "user.goodscollection",
  "user.goodscollectionlist",
  "user.vuesaveusership",
  "user.saveusership",
  "user.getshipdetail",
  "user.setdefship",
  "user.editship",
  "user.removeship",
  "user.getusership",
  "api/wxpay/user.pay",
  "user.orderevaluate",
  "user.getuserdefaultship",
  "user.issign",
  "user.sign",
  "user.mypoint",
  "user.userpointlog",
  "user.getbankcardlist",
  "user.getdefaultbankcard",
  "user.addbankcard",
  "user.removebankcard",
  "user.setdefaultbankcard",
  "user.getbankcardinfo",
  "user.editpwd",
  "user.forgotpwd",
  "user.recommend",
  "user.balancelist",
  "user.sharecode",
  "user.cash",
  "user.cashlist",
  "user.myinvite",
  "user.activationinvite",
  "coupon.getcoupon",
  "coupon.usercoupon",
  "cart.add",
  "cart.del",
  "cart.getlist",
  "cart.setnums",
  "cart.getnumber",
  "order.cancel",
  "order.del",
  "order.details",
  "order.confirm",
  "order.getlist",
  "order.create",
  "submitPreview",
  "order.getship",
  "order.getorderlist",
  "order.getorderstatusnum",
  "order.aftersaleslist",
  "order.aftersalesinfo",
  "order.aftersalesstatus",
  "order.addaftersales",
  "order.sendreship",
  "order.iscomment",
  "payments.getinfo",
  "user.getuserpoint",
  "coupon.getcouponkey",
  "store.isclerk",
  "store.storeladinglist",
  "store.ladinginfo",
  "store.lading",
  "store.ladingdel",
  "distribution_center-api-info",
  "distribution_center-api-applydistribution",
  "distribution_center-api-setstore",
  "distribution_center-api-myorder",
  "pintuan.pintuanteam",
  "lottery-api-getLotteryConfig",
  "lottery-api-lottery",
  "lottery-api-lotteryLog"
];

function baseRequest(options) {
  const token = $store.state.app.token;
  const headers = options.headers || {};

  headers["Accept"] = "application/json";
  headers["Content-Type"] = "application/x-www-form-urlencoded";
  headers["authorization"] = token;
  headers["storeid"] = storeId;
  options.headers = headers;
  if (options.login && !token) {
    toLogin();
    return Promise.reject({ msg: "未登录", toLogin: true });
  }
  var url = options.url.substring(1, options.url.length - 1);
  // 判断token是否存在
  if (methodsToken.indexOf(url) >= 0) {
    if (!token) {
      toLogin();
      return Promise.reject({ msg: "未登录", toLogin: true });
    } else {
      //data.authorization = userToken;
    }
  }
  console.log(options);
  return instance(options).then(res => {
    const data = res.data || {};
    if (res.status !== 200)
      return Promise.reject({ msg: "请求失败", res, data });

    if ([410000, 410001, 410002, 100].indexOf(data.status) !== -1) {
      toLogin();
      return Promise.reject({ msg: res.data.msg, res, data, toLogin: true });
    } else if (data.code === 200) {
      return Promise.resolve(data, res);
    } else {
      return Promise.reject({ msg: res.data.msg, res, data });
    }
  });
}

/**
 * http 请求基础类
 * 参考文档 https://www.kancloud.cn/yunye/axios/234845
 *
 */
const request = ["post", "put", "patch"].reduce((request, method) => {
  /**
   *
   * @param url string 接口地址
   * @param data object get参数
   * @param options object axios 配置项
   * @returns {AxiosPromise}
   */
  request[method] = (url, data, options = {}) => {
    return baseRequest(
      Object.assign({ url, data, method }, defaultOpt, options)
    );
  };
  return request;
}, {});

["get", "delete", "head"].forEach(method => {
  /**
   *
   * @param url string 接口地址
   * @param params object get参数
   * @param options object axios 配置项
   * @returns {AxiosPromise}
   */
  request[method] = (url, params = {}, options = {}) => {
    return baseRequest(
      Object.assign({ url, params, method }, defaultOpt, options)
    );
  };
});

export default request;
